<template>
  <div class="TabStatistics">
    <aside-tree
      title="组织"
      :tree-data="treeData"
      :loading="$loadingPlugin.getTreeData"
      :mouse-button="false"
      @currentChange="currentChange"
      @refresh="getTreeData"
    />
    <div class="content">
      <el-table-form ref="form" :model="query">
        <el-form-item label="查询日期" prop="date">
          <el-date-picker
            v-model="query.date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <template v-slot:btns>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </template>
      </el-table-form>
      <div style="margin-bottom: 10px;" class="btn-group">
        <div>
          <el-button type="primary" @click="exportFile">导出</el-button>
        </div>
      </div>
      <!-- 表格内容 -->
      <lb-table
        ref="lbTable"
        border
        highlight-current-row
        element-loading-text="加载中"
        header-row-class-name="table-row-name"
        :column="column"
        :data="tableData"
        custom-column
        show-summary
        :hight="400"
        :summary-method="getSummaries"
        @fetch="fetchData"
      />
    </div>
  </div>
</template>

<script>
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import { queryMonthAccCsmMonthlyTrackTabStatisticsList } from '@/api'
  import AsideTree from '../../components/OrgTree'
  import moment from 'dayjs'
  export default {
    name: 'addition',
    components: {
      AsideTree
    },
    data() {
      return {
        treeData: [],
        query: {
          date: [new Date(), new Date()],
          orgSNNo: '001000000000000000000'
        },
        tableData: []
      }
    },
    computed: {
      ...mapGetters(['orgList']),
      column: function() {
        return [
          {
            prop: 'orgName',
            label: '组织机构'
          },
          {
            prop: 'receivables',
            label: '月结账款',
            align: 'right',
            width: 110,
            render: (h, { row }) => <span>{row.receivables || '0.00'}</span>
          },
          {
            prop: 'billSettledFund',
            label: '月结收回',
            align: 'right',
            width: 110,
            render: (h, { row }) => <span>{row.billSettledFund || '0.00'}</span>
          },
          {
            prop: 'badMoney',
            label: '月结坏账',
            align: 'right',
            width: 110,
            render: (h, { row }) => <span>{row.badMoney || '0.00'}</span>
          },
          {
            prop: 'totalReceivable',
            label: '累计未结账款',
            align: 'right',
            width: 130,
            render: (h, { row }) => <span>{row.totalReceivable || '0.00'}</span>
          }
        ]
      }
    },
    created() {
      this.getTreeData()
    },
    methods: {
      // 获取树图数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择变化
      currentChange(current) {
        this.query.orgSNNo = current.orgSNNo
        this.search()
      },

      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.query.date && this.query.date.length > 0) {
          query[`createTime`] = moment(this.query.date[0]).format()
          query[`createTimeEnd`] = moment(this.query.date[1]).format()
        }
        delete query.date
        const res = await queryMonthAccCsmMonthlyTrackTabStatisticsList(query)
        this.tableData = res.data.rows
      },
      // 合计方法
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
            return
          }
          const values = data.map((item) => Number(item[column.property]))
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          }
        })
        // sums.forEach((v, index) => {
        //   if (index > 1) Number(v).toFixed(2)
        // })

        return sums
      },

      // 导出
      async exportFile() {
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'info'
        }).then(() => {
          this.handleDownload()
        })
      },
      async handleDownload() {
        const excel = await import('@/vendor/Export2Excel')
        const tHeader = ['组织机构', '月结账款', '月结收回', '月结坏账', '累计未结账款']
        const filterVal = [
          'orgName',
          'receivables',
          'billSettledFund',
          'badMoney',
          'totalReceivable'
        ]
        const sumData = {
          orgName: '合计:',
          receivables: 0,
          billSettledFund: 0,
          badMoney: 0,
          totalReceivable: 0
        }
        // 计算合计数据
        this.tableData.forEach(v => {
          for (const key in sumData) {
            if (sumData[key] !== '合计:') {
              sumData[key] += Number(v[key])
            }
          }
        })

        const list = JSON.parse(JSON.stringify(this.tableData))
        list.push(sumData)
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '账款统计',
          autoWidth: true,
          bookType: 'xlsx'
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map((v) =>
          filterVal.map((j) => {
            if (j === 'orgName') return v[j]
            else {
              return v[j] ? Number(v[j]).toFixed(2) : '0.00'
            }
          })
        )
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      }
    }
  }
</script>

<style lang="scss" scoped>
.TabStatistics {
  display: flex;
  // height: 630px;
  height: 100%;
  .content {
    flex: 1;
    width: 0;
    padding: 10px 10px 0 10px;
  }
}
</style>
